<?php


namespace app\index\controller;


use app\BaseController;
use app\model\Folder;
use app\model\Image;
use app\model\Settings;
use app\model\UserInfo;
use think\facade\Filesystem;

class Upload extends BaseController
{
    //设置用户的信息
    function setInc_info($uid, $size): bool
    {
        $info = UserInfo::find($uid);
        $info->files_num += 1;
        $info->use_store += $size;
        return $info->save();
    }

    //检查用户可用空间
    function check_store($uid, $size): bool
    {
        $info = UserInfo::field("uid,use_store,total_store")->find($uid);
        if ($info['total_store'] < $size + $info['use_store']) {
            return false; //空间不够
        } else {
            return true; //空间可以
        }
    }

    //上传图片文件
    public function image(): \think\response\Json
    {
        $user = $this->getUser(true);
        $setting = Settings::find("uploads");
        if ($setting->value == '0') {
            return error(10021, "服务器维护中，停止上传");
        }
        $files = $this->request->file('file');
        if (empty($files)) {
            return error(400, "没有文件");
        }
        $folder = $this->request->post('folder', 0);
        if ($folder != 0 && !Folder::where('uid', $user['uid'])->where('id', $folder)->find()) {
            return error(400, '文件夹不存在！');
        }
        $canArr = ["jpeg", "png", "jpg", "webp"];
        $fileType = $files->getOriginalExtension(); //获取文件结尾类型
        $filesize = $files->getSize() / 1000; //文件大小KIB
        $md5 = $files->md5(); //文件md5
        $max_upload = Settings::find("max_upload");
        if ($filesize > (int)$max_upload->value) {
            return error(404, "文件过大", ['maxSize' => $max_upload->value]);
        }
        $filename = $this->request->post('filename', "未命名");
        if (!$this->check_store($user['uid'], $filesize)) {
            return error(403, "储存空间不够啦");
        }
        $saveName = false;
        $width = 0;
        $height = 0;
        if (in_array(strtolower($fileType), $canArr)) {
            $imgCheck = getimagesize($files->getPathname()); //文件二次验证MIME
            if ($imgCheck) {
                $width = $imgCheck[0];
                $height = $imgCheck[1];
                $is_exist = Image::where('uid', $user['uid'])->where("md5", $md5)->find();
                if ($is_exist) {
                    return error(400, '文件已存在,请勿重复上传！', $is_exist);
                }
                $saveName = Filesystem::disk('images')->putFile('image', $files);
            }
        }

        if ($saveName) {
            $filePath = $saveName;
            $info = array(
                "addtime" => date('Y-m-d H:i:s'),
                "update_time"=>date('Y-m-d H:i:s'),
                "url" => $filePath,
                "uid" => $user['uid'],
                'size' => $filesize,
                'type' => strtolower($fileType),
                'width' => $width,
                'height' => $height,
                'md5' => $md5,
                'path' => $saveName,
                'pron' => 0,
                'folder' => $folder,
                'filename' => $filename,
            );
            try {
                Image::insertGetId($info);
            } catch (\Throwable $th) {
                //throw $th;
                return error(400, '上传失败');
            }
            $info['url'] = env("app.cdn") . '/' . $info['url'];
            $this->setInc_info($user['uid'], $filesize);
            return success("上传成功", $info);
        } else {
            return error(401, "文件格式不符合要求", ["can_type" => $canArr]);
        }
    }
}